package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-master/cache"
	"logi-master/model"
	"strconv"
	"time"
)

func PersonAdd(c *gin.Context) {
	personCode := c.PostForm("person_code")
	personName := c.PostForm("person_name")
	personPhone := c.PostForm("person_phone")
	if personCode == "" || personName == "" || personPhone == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	person := model.Person{
		PersonCode:  personCode,
		PersonName:  personName,
		PersonPhone: personPhone,
	}
	err := model.DB.Create(&person).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}

func PersonOrderAdd(c *gin.Context) {
	orderCode := c.PostForm("order_code")
	orderTo := c.PostForm("order_to")
	pid, _ := strconv.Atoi(c.PostForm("pid"))
	if orderCode == "" || orderTo == "" || pid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	personOrder := model.PersonOrder{
		OrderCode: orderCode,
		OrderTo:   orderTo,
		Pid:       pid,
	}
	err := model.DB.Create(&personOrder).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}

func PersonOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*
			SELECT
		  person_orders.id as PersonOrderId,
		  people.person_code as PersonCode,
		  people.person_name as PersonName,
		  people.person_phone as PersonPhone,
		  person_orders.order_code as order_code,
		  person_orders.order_to as OrderTo
		FROM
		  person_orders
		LEFT JOIN people ON person_orders.pid = people.id;
	*/
	var list []model.PersonOrderList
	redis_key := "person_order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("person_orders").
			Select("person_orders.id as PersonOrderId",
				"people.person_code as PersonCode",
				"people.person_name as PersonName",
				"people.person_phone as PersonPhone",
				"person_orders.order_code as order_code",
				"person_orders.order_to as OrderTo",
			).
			Joins("LEFT JOIN people ON person_orders.pid = people.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	model.DB.Model(&model.PersonOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}

func PersonOrderDetail(c *gin.Context) {

}
